import React, { useCallback, useState, useRef, useEffect } from 'react';
import Modal from './../modal/Modal';
import Table from './../table/Table';
import Search from './../search/Search';
import { TableRefProps } from './../table/interface';
import UserInfoProps from './../../interface/userInfo';
import Query from './../../interface/apiQuery';
import { columns, GET_DATA_URL } from './data';
import cls from './styles.module.scss';

const t = window.$app.t;
const pageSizeOptions = ['20'];
const fuzzyField = ['name', 'email', 'jobNumber', 'dept'];
const PLACEHOLDER = t('pleaseEnter') + fuzzyField.map((item) => t(item)).join('/');
const ROW_SELECTION_TYPE = 'radio';
const defaultQuery = { where: { userStatus: '20' } };

export const bodyStyle = {
  height: '430px',
  display: 'flex',
  flexDirection: 'column' as any,
  padding: '10px',
  position: "relative" as any
};

interface IProps {
  visible: boolean;
  onCancel(): void;
  onOk(rows: any[]): void;
  rowSelectionType?: 'radio' | 'checkbox',
  defaultSelectedUsers?: UserInfoProps[],
  title?: string;
  hideColumns?: string[];
  dfPageSizeOptions?: string[];
}

export default ({ visible, rowSelectionType, onCancel, onOk, defaultSelectedUsers, title, hideColumns, dfPageSizeOptions }: IProps) => {

  const tableRef = useRef<TableRefProps>(null);
  const cacheDefaultSelectedUsers = useRef<UserInfoProps[]>([]);
  const [selectedUsers, setSelectedUsers] = useState<UserInfoProps[]>([]);
  const [query, setQuery] = useState<any>(defaultQuery);

  useEffect(() => {
    if (defaultSelectedUsers !== cacheDefaultSelectedUsers.current && defaultSelectedUsers) {
      setSelectedUsers(defaultSelectedUsers);
      cacheDefaultSelectedUsers.current = defaultSelectedUsers;
    }
  }, [defaultSelectedUsers]);

  const rowSelectionChange = useCallback((rowKeys: string[], rows: UserInfoProps[]) => {
    const thisSelectedRows = rows.filter(item => rowKeys.includes(item.id)); // 表格所有选中行

    if (rowSelectionType === 'checkbox') {
      setSelectedUsers(thisSelectedRows.concat(cacheDefaultSelectedUsers.current));
    } else {
      setSelectedUsers(thisSelectedRows);
    }
  }, [rowSelectionType]);

  const onSearch = useCallback(
    (searchKey: string) => {
      cacheDefaultSelectedUsers.current = selectedUsers;
      setQuery({
        ...defaultQuery,
        searchKey
      });
    },
    [selectedUsers]
  );


  const removeUser = (id: string) => {
    tableRef.current?.removeSelectedRowKeys([id]);

    const newSelectedUsers = selectedUsers.filter(item => item.id !== id);
    setSelectedUsers(newSelectedUsers);
    cacheDefaultSelectedUsers.current = cacheDefaultSelectedUsers.current.filter(item => item.id !== id);
  };

  const onPageChange = useCallback((dataSource: UserInfoProps[]) => {
    if (!cacheDefaultSelectedUsers.current) return;

    const existential = cacheDefaultSelectedUsers.current.filter(item => dataSource.some(user => user.id === item.id));
    const keys = existential.map(item => item.id);

    tableRef.current?.setSelectRowKeys(keys, existential);
    cacheDefaultSelectedUsers.current = cacheDefaultSelectedUsers.current.filter(item => !keys.includes(item.id));
  }, []);

  const _onOk = useCallback(() => {
    cacheDefaultSelectedUsers.current = selectedUsers;
    onOk(selectedUsers);
  }, [selectedUsers]);

  const _onCancel = useCallback(() => {
    cacheDefaultSelectedUsers.current = defaultSelectedUsers || [];
    setSelectedUsers(defaultSelectedUsers || []);
    onCancel();
  }, [onCancel, defaultSelectedUsers]);

  const fullToggle = () => tableRef.current?.resetScroll?.();

  return (
    <Modal
      destroyOnClose
      visible={visible}
      width={976}
      title={`${window.$app.t('pleaseSelect')}${title || ''}`}
      bodyStyle={bodyStyle}
      onCancel={_onCancel}
      onOk={_onOk}
      fullToggle={fullToggle}>
      <div className={cls.main}>
        <div className={cls.waiting}>
          <Search placeholder={PLACEHOLDER} onSearch={onSearch} />
          <div className={cls.interval} />
          <Table
            reduceBoxHeight={10}
            onPageChange={onPageChange}
            ref={tableRef}
            dfPageSizeOptions={pageSizeOptions}
            rowSelectionChange={rowSelectionChange}
            rowSelectionType={rowSelectionType || ROW_SELECTION_TYPE}
            columns={hideColumns ? columns.filter(item => !hideColumns.includes(item.dataIndex)) : columns}
            query={query}
            url={GET_DATA_URL} />
        </div>
        {rowSelectionType === 'checkbox' && (
          <div className={cls.sidebar}>
            <h2>{window.$app.t('selected')}{title}<span>({selectedUsers.length})</span></h2>
            <ul>
              {selectedUsers.map(item => (
                <li key={item.id}>
                  <span>{item.name}</span>
                  <span onClick={() => removeUser(item.id)} className={cls.delAction}>{window.$app.t('delete')}</span>
                </li>
              ))}
            </ul>
          </div>
        )}
      </div>
    </Modal>
  );
};